<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Badge,
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [devices: IOTDevice[]];
}>();

// IOT设备状态枚举
enum DeviceStatus {
  ERROR = 'error', // 故障
  MAINTENANCE = 'maintenance', // 维护中
  OFFLINE = 'offline', // 离线
  ONLINE = 'online', // 在线
}

// IOT设备接口
interface IOTDevice {
  id: string;
  name: string;
  type: string;
  status: DeviceStatus;
  lastUpdate: string;
  battery?: number;
  signal?: number;
}

// Props
interface Props {
  roomId: string;
  roomNumber: string;
  devices: IOTDevice[];
}

// 设备数据
const devicesData = ref<IOTDevice[]>([...props.devices]);

// 设备类型选项
const deviceTypeOptions = [
  { label: '智能门锁', value: 'lock' },
  { label: '空调控制器', value: 'ac' },
  { label: '智能电表', value: 'meter' },
  { label: '摄像头', value: 'camera' },
  { label: '热水器', value: 'water-heater' },
  { label: '照明控制', value: 'lighting' },
  { label: '窗帘控制', value: 'curtain' },
  { label: '烟雾报警器', value: 'smoke-alarm' },
  { label: '温湿度传感器', value: 'sensor' },
  { label: '其他', value: 'other' },
];

// 设备状态选项
const deviceStatusOptions = [
  { label: '在线', value: DeviceStatus.ONLINE },
  { label: '离线', value: DeviceStatus.OFFLINE },
  { label: '故障', value: DeviceStatus.ERROR },
  { label: '维护中', value: DeviceStatus.MAINTENANCE },
];

// 表格列配置
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    customRender: ({ text }: { text: string }) => {
      const option = deviceTypeOptions.find((opt) => opt.value === text);
      return option?.label || text;
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ text }: { text: DeviceStatus }) => {
      const statusConfig = {
        [DeviceStatus.ONLINE]: { color: 'green', text: '在线' },
        [DeviceStatus.OFFLINE]: { color: 'red', text: '离线' },
        [DeviceStatus.ERROR]: { color: 'orange', text: '故障' },
        [DeviceStatus.MAINTENANCE]: { color: 'blue', text: '维护中' },
      };
      const config = statusConfig[text];
      return config ? h(Tag, { color: config.color }, () => config.text) : text;
    },
  },
  {
    title: '电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 80,
    customRender: ({ text }: { text?: number }) => {
      if (text === undefined) return '-';
      return h(Badge, {
        color: text > 20 ? 'green' : text > 10 ? 'orange' : 'red',
        count: `${text}%`,
      });
    },
  },
  {
    title: '信号强度',
    dataIndex: 'signal',
    key: 'signal',
    width: 100,
    customRender: ({ text }: { text?: number }) => {
      if (text === undefined) return '-';
      const signalConfig = {
        excellent: { color: 'green', text: '优秀' },
        good: { color: 'blue', text: '良好' },
        fair: { color: 'orange', text: '一般' },
        poor: { color: 'red', text: '较差' },
      };
      let level = 'poor';
      if (text >= 80) level = 'excellent';
      else if (text >= 60) level = 'good';
      else if (text >= 40) level = 'fair';

      const config = signalConfig[level as keyof typeof signalConfig];
      return config ? h(Tag, { color: config.color }, () => config.text) : text;
    },
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    customRender: ({ record }: { record: IOTDevice }) => {
      return h(Space, {}, [
        h(
          Button,
          {
            onClick: () => editDevice(record),
            size: 'small',
            type: 'link',
          },
          () => '编辑',
        ),
        h(
          Button,
          {
            onClick: () => testDevice(record),
            size: 'small',
            type: 'link',
          },
          () => '测试',
        ),
        h(
          Button,
          {
            danger: true,
            onClick: () => removeDevice(record),
            size: 'small',
            type: 'link',
          },
          () => '删除',
        ),
      ]);
    },
  },
];

// 表单相关
const formRef = ref();
const formModel = reactive({
  name: '',
  type: 'lock',
  status: DeviceStatus.ONLINE,
  battery: undefined as number | undefined,
  signal: undefined as number | undefined,
});

// 模态框状态
const modalVisible = ref(false);
const modalTitle = ref('添加设备');
const isEdit = ref(false);
const currentDeviceId = ref('');

// 添加设备
const addDevice = () => {
  modalTitle.value = '添加设备';
  isEdit.value = false;
  resetForm();
  modalVisible.value = true;
};

// 编辑设备
const editDevice = (device: IOTDevice) => {
  modalTitle.value = '编辑设备';
  isEdit.value = true;
  currentDeviceId.value = device.id;
  Object.assign(formModel, device);
  modalVisible.value = true;
};

// 测试设备
const testDevice = (device: IOTDevice) => {
  Modal.info({
    title: `设备测试 - ${device.name}`,
    content: `
      <div>
        <p><strong>设备名称:</strong> ${device.name}</p>
        <p><strong>设备类型:</strong> ${deviceTypeOptions.find((opt) => opt.value === device.type)?.label}</p>
        <p><strong>当前状态:</strong> ${deviceStatusOptions.find((opt) => opt.value === device.status)?.label}</p>
        <p><strong>最后更新:</strong> ${device.lastUpdate}</p>
        ${device.battery ? `<p><strong>电量:</strong> ${device.battery}%</p>` : ''}
        ${device.signal ? `<p><strong>信号强度:</strong> ${device.signal}%</p>` : ''}
        <p style="margin-top: 16px; color: #1890ff;">正在测试设备连接...</p>
      </div>
    `,
  });

  // 模拟测试过程
  setTimeout(() => {
    message.success('设备测试完成，连接正常');
  }, 2000);
};

// 删除设备
const removeDevice = (device: IOTDevice) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除设备"${device.name}"吗？`,
    onOk: () => {
      const index = devicesData.value.findIndex((d) => d.id === device.id);
      if (index !== -1) {
        devicesData.value.splice(index, 1);
        emit('update', devicesData.value);
        message.success('设备删除成功');
      }
    },
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(formModel, {
    name: '',
    type: 'lock',
    status: DeviceStatus.ONLINE,
    battery: undefined,
    signal: undefined,
  });
};

// 保存设备
const saveDevice = async () => {
  try {
    await formRef.value?.validate();

    if (isEdit.value) {
      // 编辑设备
      const index = devicesData.value.findIndex(
        (device) => device.id === currentDeviceId.value,
      );
      if (index !== -1) {
        devicesData.value[index] = {
          ...devicesData.value[index],
          ...formModel,
          lastUpdate: new Date().toISOString(),
        };
      }
      message.success('设备信息更新成功');
    } else {
      // 新增设备
      const newDevice: IOTDevice = {
        id: Date.now().toString(),
        ...formModel,
        lastUpdate: new Date().toISOString(),
      };
      devicesData.value.push(newDevice);
      message.success('设备添加成功');
    }

    emit('update', devicesData.value);
    modalVisible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 批量操作
const selectedRowKeys = ref<string[]>([]);

const onSelectionChange = (keys: string[]) => {
  selectedRowKeys.value = keys;
};

const batchTest = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要测试的设备');
    return;
  }

  Modal.info({
    title: '批量测试',
    content: `正在测试选中的 ${selectedRowKeys.value.length} 个设备...`,
  });

  setTimeout(() => {
    message.success('批量测试完成');
  }, 3000);
};

const batchRemove = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的设备');
    return;
  }

  Modal.confirm({
    title: '批量删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个设备吗？`,
    onOk: () => {
      selectedRowKeys.value.forEach((key) => {
        const index = devicesData.value.findIndex(
          (device) => device.id === key,
        );
        if (index !== -1) {
          devicesData.value.splice(index, 1);
        }
      });
      selectedRowKeys.value = [];
      emit('update', devicesData.value);
      message.success('批量删除成功');
    },
  });
};

// 设备统计
const deviceStatistics = computed(() => {
  const total = devicesData.value.length;
  const online = devicesData.value.filter(
    (d) => d.status === DeviceStatus.ONLINE,
  ).length;
  const offline = devicesData.value.filter(
    (d) => d.status === DeviceStatus.OFFLINE,
  ).length;
  const error = devicesData.value.filter(
    (d) => d.status === DeviceStatus.ERROR,
  ).length;
  const maintenance = devicesData.value.filter(
    (d) => d.status === DeviceStatus.MAINTENANCE,
  ).length;

  return { total, online, offline, error, maintenance };
});

onMounted(() => {
  console.log('IOT设备管理组件已加载');
});
</script>

<template>
  <div class="iot-device-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>IOT设备管理 - {{ roomNumber }}</h2>
      <Space>
        <Button type="primary" @click="addDevice">
          <template #icon>
            <IconifyIcon icon="mdi:plus" />
          </template>
          添加设备
        </Button>
        <Button :disabled="selectedRowKeys.length === 0" @click="batchTest">
          <template #icon>
            <IconifyIcon icon="mdi:test-tube" />
          </template>
          批量测试
        </Button>
        <Button
          :disabled="selectedRowKeys.length === 0"
          danger
          @click="batchRemove"
        >
          <template #icon>
            <IconifyIcon icon="mdi:delete" />
          </template>
          批量删除
        </Button>
      </Space>
    </div>

    <!-- 设备统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ deviceStatistics.total }}</div>
            <div class="stat-label">总设备数</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number online">{{ deviceStatistics.online }}</div>
            <div class="stat-label">在线设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number offline">
              {{ deviceStatistics.offline }}
            </div>
            <div class="stat-label">离线设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number error">{{ deviceStatistics.error }}</div>
            <div class="stat-label">故障设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number maintenance">
              {{ deviceStatistics.maintenance }}
            </div>
            <div class="stat-label">维护设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{
                deviceStatistics.total > 0
                  ? Math.round(
                      (deviceStatistics.online / deviceStatistics.total) * 100,
                    )
                  : 0
              }}%
            </div>
            <div class="stat-label">在线率</div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 设备列表 -->
    <Card class="table-card">
      <Table
        :columns="columns"
        :data-source="devicesData"
        :row-selection="{
          selectedRowKeys,
          onChange: onSelectionChange,
        }"
        :pagination="{
          total: devicesData.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }"
        row-key="id"
      />
    </Card>

    <!-- 添加/编辑设备模态框 -->
    <Modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="saveDevice"
      @cancel="modalVisible = false"
    >
      <Form
        ref="formRef"
        :model="formModel"
        :rules="{
          name: [{ required: true, message: '请输入设备名称' }],
          type: [{ required: true, message: '请选择设备类型' }],
        }"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="设备名称" name="name">
              <Input
                v-model:value="formModel.name"
                placeholder="请输入设备名称"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="设备类型" name="type">
              <Select
                v-model:value="formModel.type"
                :options="deviceTypeOptions"
                placeholder="选择设备类型"
              />
            </Form.Item>
          </Col>
        </Row>

        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="设备状态" name="status">
              <Select
                v-model:value="formModel.status"
                :options="deviceStatusOptions"
                placeholder="选择设备状态"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="电量(%)" name="battery">
              <InputNumber
                v-model:value="formModel.battery"
                :min="0"
                :max="100"
                style="width: 100%"
                placeholder="请输入电量"
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item label="信号强度(%)" name="signal">
          <InputNumber
            v-model:value="formModel.signal"
            :min="0"
            :max="100"
            style="width: 100%"
            placeholder="请输入信号强度"
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .iot-device-management {
    padding: 8px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .statistics-row {
    margin-bottom: 8px;
  }

  .stat-number {
    font-size: 20px;
  }
}

.iot-device-management {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.statistics-row {
  margin-bottom: 16px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 8px;
}

.stat-number {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.stat-number.online {
  color: #52c41a;
}

.stat-number.offline {
  color: #ff4d4f;
}

.stat-number.error {
  color: #fa8c16;
}

.stat-number.maintenance {
  color: #722ed1;
}

.stat-label {
  font-size: 12px;
  color: #8c8c8c;
}

.table-card {
  background: white;
}
</style>
